package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.TopoEdge;
import com.ruoyi.system.domain.TopoNode;
import com.ruoyi.system.domain.vo.TopoVO;
import com.ruoyi.system.mapper.TopoNodeMapper;
import com.ruoyi.system.service.ITopoNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TopoNodeServiceImpl implements ITopoNodeService {

    @Autowired
    private TopoNodeMapper topoNodeMapper;

    public Map<String, ArrayList<TopoNode>> get_add_delete_list(List<TopoNode> newTopoNodes, List<TopoNode> originTopoNodes,Long topoVoId) {
        ArrayList<TopoNode> add_list = new ArrayList<>();
        ArrayList<TopoNode> delete_list = new ArrayList<>();
        Map<String, ArrayList<TopoNode>> result = new HashMap<>();

        //寻找需要新增的,遍历前端传过来的数组和数据库中已有的数据比较，如果前端传过来的元素在数据库中找不到的话，那么新增它
        for (TopoNode newTopoNode : newTopoNodes) {
            Boolean flag = true;
            for (TopoNode originTopoNode : originTopoNodes) {
                if (Objects.equals(newTopoNode.getNodeId(), originTopoNode.getNodeId())) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                newTopoNode.setTopoId(topoVoId);
                add_list.add(newTopoNode);
            }
        }

        //寻找需要删除的节点
        for (TopoNode originTopoEdge : originTopoNodes) {
            Boolean flag = true;
            for (TopoNode newTopoNode : newTopoNodes) {
                if (Objects.equals(newTopoNode.getNodeId(), originTopoEdge.getNodeId())) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                delete_list.add(originTopoEdge);
            }
        }
        result.put("add", add_list);
        result.put("delete", delete_list);
        return result;
    }

    @Override
    public void addTopoNode(TopoVO topoVO) {
        List<TopoNode> newTopoNodes = topoVO.getNodes();
        List<TopoNode> originTopoNodes = topoNodeMapper.selectByTopoId(topoVO.getTopoId());
        Map<String, ArrayList<TopoNode>> result = get_add_delete_list(newTopoNodes, originTopoNodes,topoVO.getTopoId());
        ArrayList<TopoNode>addList= result.get("add");
        ArrayList<TopoNode>deleteList = result.get("delete");
//        ArrayList<Long> delete_ids = new ArrayList<>();
        Long[]deleteids = new Long[deleteList.size()];
//        for(TopoNode topoNode:deleteList){
//            delete_ids.add(topoNode.getNodeId());
//        }

        for(int i = 0;i<deleteList.size();i++){
            deleteids[i]=deleteList.get(i).getNodeId();
        }
        if(!addList.isEmpty()){
            topoNodeMapper.addTopoNodes(addList);
        }
        if(deleteids.length!=0){
            topoNodeMapper.deleteByTopoNodeIds(deleteids);
        }

    }
}
